# encoding:utf-8
# !/usr/bin/env python
import cv2
import requests
import urllib2
from PIL import Image
from flask import Flask, render_template, jsonify, request, send_from_directory,redirect, url_for, Response, json, make_response
import os
import datetime
from datetime import timedelta
import random
import string
from flask_cors import cross_origin

import Convert
from flask_cors import CORS
import time

#from weixin.login import WeixinLogin
from weixin import WXAPPAPI
from weixin.pay import WXAppPay

app = Flask(__name__, static_url_path='')
# r'/*' 是通配符，让本服务器所有的URL 都允许跨域请求
CORS(app, resources=r'/*')
app.debug = True

app_id = 'wx7ca60df2cac39e1f'
app_secret = '955b395d2ab8c2540ec1432a7cfe09cb'
mch_id = '1499183902'
mch_key = 'DxMLsdJz7ioXvrVUsL92111DxMLsdJ17'
# wx_login = WeixinLogin(app_id, app_secret)
wxpay = WXAppPay(appid=app_id, mch_id=mch_id, partner_key=mch_key, notify_url='qq.com')



UPLOAD_FOLDER = 'upload/header'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)
basedir = os.path.abspath(os.path.dirname(__file__))
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'gif', 'GIF','jpeg','JPEG'])

imgdir_map = {}

class Pic_str:
    def create_uuid(self): #生成唯一的图片的名称字符串，防止图片显示时的重名问题
        nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S");  # 生成当前时间
        randomNum = random.randint(0, 100);  # 生成的随机整数n，其中0<=n<=100
        if randomNum <= 10:
            randomNum = str(0) + str(randomNum);
        uniqueNum = str(nowTime) + str(randomNum);
        return uniqueNum;

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@app.route('/deepface/upload')
def upload_test():
    return render_template('up.html')

# @app.route("/deepface/login")
# def login():
#     openid = request.cookies.get("openid")
#     #openid = '234324234'
#     next = '/deepface/web/index.html'
#     if openid:
#         return redirect(next)
#
#     callback = url_for("deepface/authorized", next=next, _external=True)
#     url = wx_login.authorize(callback, "snsapi_base")
#     return redirect(url)


# @app.route("/deepface/login",methods=['GET','POST'])
# def authorized():
#     header = request.headers
#     print header
#     code = request.args.get("code")
#     if not code:
#         return jsonify({"code": 4000, "msg": "ERR_INVALID_CODE"})
#     data = wx_login.access_token(code)
#     openid = data.openid
#     access_token = data.access_token
#
#     resdata = wx_login.userinfo(access_token,openid)
#     headimgurl = resdata.headimgurl
#     str = headimgurl.split("//")[1]
#     headimgurl = 'https:'+"//"+str
#     return jsonify({"code": 0, "msg": "success",
#                     "data": {"url": openid, "headimgurl":headimgurl}})


# 上传文件
@app.route('/deepface/up_photo', methods=['POST'], strict_slashes=False)
@cross_origin()
def api_upload():
    file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    video = request.args.get("video")
    f = request.files['upload']
    time_start = time.time()
    if f and allowed_file(f.filename):
        uuid = Pic_str().create_uuid()
        new_filename = Pic_str().create_uuid() + '.png'
        f.save(os.path.join(file_dir, new_filename))

        file_path = file_dir+"/"+new_filename

        video_convert(file_path,uuid,video)
        video_name = uuid+".mp4"
        pic = uuid+".jpg"
        print video_name
        print('time cost', time.time() - time_start, 's')
        return jsonify({"code": 0, "msg": "上传成功",
                        "pic":pic,"width":640,"height":592,"video":video_name})
    else:
        return jsonify({"code": 1001, "msg": "上传失败"})

@app.route('/deepface/weixin_header', methods=['POST'])
def api_uploadheader():
    time_start = time.time()
    file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
    params = json.loads(request.get_data())
    video = params.get("video")
    headimgurl = params.get("headimgurl")
    if not headimgurl:
        return jsonify({"code": 1002, "msg": "获取微信头像失败,请重新登陆"})
    res = requests.get(headimgurl)
    uuid = Pic_str().create_uuid()
    new_filename = uuid+ '.png'
    file_path = file_dir + "/" + new_filename
    video_name = uuid + ".mp4"
    with open(file_path, "wb") as f:
        f.write(res.content)
    f.close()
    video_convert(file_path, uuid, video)
    print video_name
    print('time cost', time.time() - time_start, 's')
    return jsonify({"code": 0, "msg": "success",
                    "data": {"pic":uuid+".jpg", "video": video_name,  "width": 640, "height": 592}})

@app.route('/deepface/payment', methods=['POST'])
def api_payment():
    params = json.loads(request.get_data())
    code = params.get("code")

    oauth_code = "https://api.weixin.qq.com/sns/jscode2session?appid=" + app_id + "&secret=" + app_secret + "&js_code=" + code + "&grant_type=authorization_code";
    response = urllib2.urlopen(oauth_code)
    result = response.read()
    app.logger.debug(result)

    openid = json.loads(result)['openid']

    out_trade_no = ''
    for _ in range(10):
        out_trade_no += random.choice(string.ascii_letters + string.digits)

    result = wxpay.unifiedorder(body=u'unlock',total_fee='1',openid=openid,trade_type='JSAPI',out_trade_no=out_trade_no)
    app.logger.debug(result)
    ret = wxpay.build_wxapp_sign(result, 'JSAPI')
    app.logger.debug(result)

    return json.dumps(ret)

@app.route('/deepface/download/<string:filename>', methods=['GET'])
def download(filename):
    fullfilename = os.path.join('static/deepface/video', filename)

    # 流式读取
    def send_file():
        store_path = fullfilename
        with open(store_path, 'rb') as targetfile:
            while 1:
                data = targetfile.read(20 * 1024 * 1024)  # 每次读取20M
                if not data:
                    break
                yield data

    response = Response(send_file(), content_type='application/octet-stream')
    response.headers["Content-disposition"] = 'attachment; filename=%s' % filename  # 如果不加上这行代码，导致下图的问题
    return response


def video_convert(header_path,video_name,video):
    header = Convert.img_deal(header_path)
    header = Image.fromarray(cv2.cvtColor(header, cv2.COLOR_BGR2RGBA))
    headers = [header.resize((49, 49)),header.resize((38, 38))]
    video_save_path = r'./static/deepface/video/' + video_name

    yuan = [Image.open(r'./upload/yuan1.png').resize((51, 51)),Image.open(r'./upload/yuan1.png').resize((40,40))]

    image = imgdir_map[video]
    time_start = time.time()
    print('Converting image .............')
    print video
    if video == "520520_free" :
       image = pase_520520_free(image, headers, yuan, video_name)
    else:
       image = pase_520520_pay(image, headers, yuan, video_name)
    print('Convert image success')
    time_end = time.time()
    print('Converting image time cost', time_end - time_start, 's')
    Convert.img_convert_video(video_save_path,image)

def pase_520520_free(image,headers,yuan,video_name) :
    location = (262, 208)
    for i in range(len(image)):
        img1 = image[i]
        img2 = headers[0]
        img3 = yuan[0]
        if i >= 100 and i < 102:
            location = (262, 219)
        elif i >= 102 and i < 104:
            location = (262, 218)
        elif i >= 104 and i < 106:
             location = (262, 217)
        elif i >= 106 and i < 178:
             location = (262, 216)
        elif i == 178:
             location = (276, 216)
        elif i == 179:
            location = (304, 216)
        elif i == 180 :
            location = (334, 216)
        elif i == 181:
            location = (416, 216)
        elif i >181 and i< 219:
            continue
        elif i == 219:
             image[i] = image[i-1]
             continue
        elif i > 219:
            img2 = headers[1]
            img3 = yuan[1]
            location = (416, 98)
        image[i] = Convert.img_paste(img1,img2,img3,location)
        if i == 0 :
            image[i].save(r'./static/deepface/img/' + video_name+".jpg")
    return image

def pase_520520_pay(image, headers, yuan, video_name):
    location = (268, 248)
    for i in range(len(image)):
        img1 = image[i]
        img2 = headers[0]
        img3 = yuan[0]
        if i >= 120 and i < 121:
            location = (268, 258)
        elif i >= 121 and i < 122:
            location = (268, 257)
        elif i >= 122 and i < 123:
            location = (268, 256)
        elif i >= 123 and i < 157:
            location = (268, 256)
        elif i == 157:
            location = (298, 256)
        elif i == 158 and i == 159:
            location = (339, 256)
        elif i == 160:
            location = (422, 256)
        elif i > 160 and i < 176:
            continue
        elif i == 176:
            image[i] = image[i - 1]
            continue
        elif i == 177:
            img2 = headers[1]
            img3 = yuan[1]
            location = (406, 98)
        elif i > 177:
            img2 = headers[1]
            img3 = yuan[1]
            location = (418, 98)
        image[i] = Convert.img_paste(img1, img2, img3, location)
        if i == 0:
            image[i].save(r'./static/deepface/img/' + video_name + ".jpg")
    return image

def read_img():
    img_dir = os.listdir("./video/img")
    for i in range(len(img_dir)):
        images = os.listdir("./video/img/"+img_dir[i])
        img_list = list(range(len(images)))
        for n in range(len(images)):
            path = "./video/img/"+img_dir[i]+"/"+str(n+1)+".jpg"
            image = Image.open(path)
            img_list[n] = image
        imgdir_map[img_dir[i]] = img_list

if __name__ == '__main__':
    read_img()
    app.run(host='0.0.0.0',port=5000,debug=True)


